package com.bigfans.orderservice.listeners;

import com.bigfans.framework.kafka.KafkaConsumerBean;
import com.bigfans.framework.kafka.KafkaListener;
import com.bigfans.model.event.payment.OrderPaidEvent;
import com.bigfans.model.event.payment.PayMethodChangedEvent;
import com.bigfans.orderservice.api.clients.PayMethodServiceClient;
import com.bigfans.orderservice.model.PayMethod;
import com.bigfans.orderservice.service.OrderService;
import com.bigfans.orderservice.service.PayMethodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author lichong
 * @create 2018-03-15 上午7:25
 **/
@KafkaConsumerBean
@Component
public class PaymentListener {

    @Autowired
    private PayMethodServiceClient payMethodServiceClient;
    @Autowired
    private PayMethodService payMethodService;
    @Autowired
    private OrderService orderService;

    @KafkaListener
    public void on(PayMethodChangedEvent payMethodChangedEvent) {
        try {
            String methodId = payMethodChangedEvent.getMethodId();
            CompletableFuture<PayMethod> future = payMethodServiceClient.getPayMethod(methodId);
            PayMethod payMethod = future.get();
            payMethodService.update(payMethod);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @KafkaListener
    public void on(OrderPaidEvent event) {
        try {
            String orderId = event.getOrderId();
            orderService.updateStatusToPaid(orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
